import pymysql
class DBUtil:
    #封装建立连接方法
    conn =None
    @classmethod
    def __connect_db(cls):
        cls.conn = pymysql.Connect(host="211.103.136.244",port=7061,user="student",
                            password="iHRM_student_2022",database="ihrm",charset="utf8")
        return cls.conn
    #封装关闭连接的方法
    @classmethod
    def __clos_db(cls):
        cls.conn.close()
    @classmethod
    def query_db(cls,sql):
        cursor =None
        result =None
        try:

            #建立连接
            cls.conn =cls.__connect_db()
            #获取游标
            cursor =cls.conn.cursor()
            #执行sql,返回结果
            cursor.execute(sql)
            result =cursor.fetchone()
        except Exception as err:
            print("查询数据时报错:",str(err))
        finally:
            #关闭游标
            cursor.close()
            #关闭连接
            cls.__clos_db()
            return result
    @classmethod
    def uid_db(cls,sql):
        cursor =None
        try:
            # 建立连接
            cls.conn =cls.__connect_db()

            # 获取游标
            cursor =cls.conn.cursor()
            # 执行sql,返回影响的行数
            cursor.execute(sql)
            affect_rows =cls.conn.affected_rows()
            print('影响的行数为:',affect_rows)
            cls.conn.commit()
        except Exception as err:
            print("增删改数据库时报错:",str(err))
            cls.conn.rollback()
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__clos_db()